package Herramientas;

import java.awt.Desktop;
import java.awt.print.PrinterJob;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ServicioImpresion {

    public static void main(String args[], String rutaArchivo) throws IOException {

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(rutaArchivo.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (inputStream == null) {
            return;
        }

        DocFlavor docFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc document = new SimpleDoc(inputStream, docFormat, null);

        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

        if (defaultPrintService != null) {
            DocPrintJob printJob = defaultPrintService.createPrintJob();
            try {
                printJob.print(document, attributeSet);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("No existen impresoras instaladas");
        }
        inputStream.close();
    }

    public void imprimir(String rutaDoc) {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.printDialog();
        String impresora = job.getPrintService().getName();

        //ESTE ES TU CÓDIGO
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
        java.io.File fichero = new java.io.File(rutaDoc);
        if (desktop.isSupported(Desktop.Action.PRINT)) {
            try {
                try {
                    Process pr = Runtime.getRuntime().exec("Rundll32 printui.dll,PrintUIEntry /y /n \"" + impresora + "\"");
                } catch (Exception ex) {
                    System.out.println("Ha ocurrido un error al ejecutar el comando. Error: " + ex);
                }
                desktop.print(fichero);
            } catch (Exception e) {
                System.out.print("El sistema no permite imprimir usando la clase Desktop");
                e.printStackTrace();
            }
        } else {
            System.out.print("El sistema no permite imprimir usando la clase Desktop");
        }
    }
}
